package com.library.controller;

import com.library.dao.UserDao;
import com.library.dao.impl.UserDaoImpl;
import com.library.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginIn")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String type = request.getParameter("type");
        String captcha = request.getParameter("captcha");
        
        // 验证码校验
        HttpSession session = request.getSession();
        String realCaptcha = (String) session.getAttribute("verifyCode");
        if (realCaptcha == null || !realCaptcha.equalsIgnoreCase(captcha)) {
            request.setAttribute("msg", "验证码错误！");
            response.sendRedirect(request.getContextPath() + "/pages/login.jsp");
            return;
        }
        
        UserDao userDao = new UserDaoImpl();
        boolean loginSuccess = false;
        
        try {
            // 根据用户类型选择验证方法
            if ("1".equals(type)) { // 管理员登录
                loginSuccess = userDao.adminLogin(username, password);
            } else if ("2".equals(type)) { // 读者登录
                loginSuccess = userDao.readerLogin(username, password);
            }
            
            if (loginSuccess) {
                // 登录成功
                User user=  new User();
                user.setUsername(username);
                user.setAdminType(Integer.valueOf(type));
                session.setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/pages/index.jsp");
            } else {
                // 登录失败
                request.setAttribute("msg", "用户名或密码错误！");
            request.getRequestDispatcher("/pages/login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误，请稍后重试！");
            response.sendRedirect(request.getContextPath() + "/pages/login.jsp");
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}